<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        div{padding:10px;margin:10px;}
    </style>
</head>
<body>
    
</body>
<script>
    // 组合器

    // 有子对象的对象：Box
    function Box(id){
        this.ele = document.createElement("div");
        this.ele.id = id;
        this.children = [];

        this.add = function(child){
            this.children.push(child);
            this.ele.appendChild( child.ele );
        }
        this.remove = function(child){
            const idx = this.children.indexOf(child)
            if(idx !== -1){
                this.children.splice(idx, 1);
            }
            child.ele.remove();
        }
        this.addBorder = function(){
            this.ele.style.border = "solid 2px black";
            this.children.forEach(val=>{
                val.addBorder();
            })
        }
        this.removeBorder = function(){
            this.ele.style.border = "none";
            this.children.forEach(val=>{
                val.removeBorder();
            })
        }
    }

    // 没有子对象的对象：Img
    function Img(src){
        this.ele = document.createElement("img");
        this.ele.src = src;

        this.add = function(child){
            console.log("这是一个Img对象，不能添加子对象了")
        }
        this.remove = function(child){
            console.log("这是一个Img对象，没有子对象可删除了")
        }
        this.addBorder = function(){
            this.ele.style.border = "solid 2px black";
        }
        this.removeBorder = function(){
            this.ele.style.border = "none";
        }
    }
    
    const b1 = new Box("b1");
    const b2 = new Box("b2");
    const b3 = new Box("b3");
    const b4 = new Box("b4");

    document.body.appendChild( b1.ele );
    
    b1.add( b2 );
    b1.add( b3 );
    
    b3.add( b4 );

    const i1 = new Img(1)
    const i2 = new Img(2)
    const i3 = new Img(3)
    const i4 = new Img(4)

    // 无效执行
    // i1.add();
    // i2.add();
    // i3.add();
    // i4.add();

    b1.add( i4 );
    b2.add( i3 );
    b3.add( i2 );
    b4.add( i1 );

    // b3.remove( b4 );

    b1.addBorder();

    // i3.removeBorder();


    
</script>
</html>